package com.zfzs.post.modules.goods.service.impl;

import com.zfzs.post.model.dto.QuerTypePageDTO;
import com.zfzs.post.model.vo.GoodsOrderVO;
import com.zfzs.post.model.vo.QueryAgentPageListVO;
import com.zfzs.post.model.vo.TerminalInfoVO;
import com.zfzs.post.modules.goods.domain.GoodOrder;
import com.zfzs.post.modules.goods.repository.GoodOrderRepository;
import com.zfzs.post.modules.goods.service.GoodOrderService;
import com.zfzs.post.modules.goods.service.dto.GoodOrderQueryCriteria;
import com.zfzs.post.modules.goods.service.mapper.GoodOrderMapper;
import com.zfzs.post.modules.goods.service.mybatis.IGoodsOrderService;
import com.zfzs.post.page.JpaPageHelper;
import com.zfzs.post.utils.PageUtil;
import com.zfzs.post.utils.QueryHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.criteria.Predicate;

/**
 * 商品订单
 *
 * @author ck
 * @date 2019-10-18
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GoodOrderServiceImpl implements GoodOrderService {

    @Autowired
    private GoodOrderRepository goodOrderRepository;

    @Autowired
    private GoodOrderMapper goodOrderMapper;

    @Autowired
    private IGoodsOrderService iGoodsOrderService;

    @Override
    public Page<GoodOrder> queryAll(GoodOrderQueryCriteria criteria, Pageable pageable) {
        Page<GoodOrder> page = goodOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return page;
    }

    @Override
    public Object queryAll(GoodOrderQueryCriteria criteria) {
        return goodOrderMapper.toDto(goodOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public GoodOrder findById(Integer id) {
        Optional<GoodOrder> goodOrder = goodOrderRepository.findById(id);
        return goodOrder.isPresent()?goodOrder.get():null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GoodOrder create(GoodOrder resources) {
        resources.setCreateDate(new Timestamp(System.currentTimeMillis()));
        resources.setCreateTime(new Timestamp(System.currentTimeMillis()));
        resources.setPayState(0);
        return goodOrderRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(GoodOrder resources) {
        Optional<GoodOrder> optionalGoodOrder = goodOrderRepository.findById(resources.getOrderId());
        if (optionalGoodOrder.isPresent()) {
            GoodOrder goodOrder = optionalGoodOrder.get();
            goodOrder.copy(resources);
            goodOrder.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            goodOrderRepository.save(goodOrder);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        goodOrderRepository.deleteById(id);
    }

    @Override
    public int queryCountByAgentIds(Long channelId, List<Long> ids, String startDate, String endDate) {
        return goodOrderRepository.queryCountByAgentIds(channelId, ids, startDate, endDate);
    }

    @Override
    public JpaPageHelper queryOrderByAgentIds(QuerTypePageDTO dto) {
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        Long channelId = dto.getChannelId();
        String endDate =  dto.getEndDate();
        List<Long> ids = dto.getIds();
        String startDate = dto.getStartDate();
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);//借助计算起始位置
        // 计算数据总条数
        int total = goodOrderRepository.queryOrderByAgentIdsCount(channelId, ids, startDate, endDate);
        List<Map<String, Object>> list = goodOrderRepository.queryOrderByAgentIdsList(channelId, ids, startDate, endDate,pageRequest.getOffset(),pageRequest.getPageSize());
        JpaPageHelper<QueryAgentPageListVO> page = new JpaPageHelper<>(list,pageSize,pageNum,total);
        // 转换分页数据
        page.setResult(list);
        return page;
    }

    @Override
    public GoodOrder findByOrderNo(String orderNo) {
        return goodOrderRepository.findByOrderNo(orderNo);
    }

    @Override
    public Page<GoodOrder> getOwnerList(Long agentId, Integer status, Integer pageNo) {
        Specification<GoodOrder> specification= (Specification<GoodOrder>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if(status!=0){
                predicateList.add(cb.equal(root.get("status").as(Integer.class),status));
            }
            predicateList.add(cb.equal(root.get("agentId").as(Long.class),agentId));

            Predicate[] predicates = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(predicates)).getRestriction();

        };
        Sort sort=Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(pageNo,10,sort);

        return goodOrderRepository.findAll(specification,pageable);


    }

    @Override
    public int queryOrderByAgentIdsSum(Long channelId, List<Long> ids, String startDate, String endDate) {
        return goodOrderRepository.queryOrderByAgentIdsSum(channelId, ids, startDate, endDate);
    }

    @Override
    public JpaPageHelper<GoodsOrderVO> findGoodsOrderPage(GoodOrderQueryCriteria criteria, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size);
        int count=iGoodsOrderService.getCountGoodOrderPage(criteria);
        List<Map<String,Object>> records = iGoodsOrderService.getListGoodOrderPage(criteria, (int) pageable.getOffset(), pageable.getPageSize());
        JpaPageHelper<GoodsOrderVO> jpaPage = new JpaPageHelper<>(records,size,page,count);
        jpaPage.setResult(records);
        // 转换分页数据
        return jpaPage;
    }


}